package pack;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

class Handler {
	private static ServerSocket s = null;
	private Socket client = null;
	private ArrayList<Socket> clients = new ArrayList<Socket>();

	public static final int lowPortLimit = 8000;
	public static final int highPortLimit = 8199;

	// @ invariant port > lowPortLimit && port > highPortLimit;
	// @ invariant port != null;
	// @ invariant getClient()!=null;
	int /* @ spec_public non_null @ */port = 8080;

	public Handler() {
		s = createServer(port);
	}

	// It waits for a new socket connection and trow it for a thread
	public void listen() {
		System.out.println("Listining on port " + s.getLocalPort());
		while (true) {
			try {
				setClient(s.accept());
				// this.client = s.accept();
				System.out.println("Connections: " + clients.size());
				clients.add(getClient());
				new Transeunte(getClient());
			} catch (IOException e) {
				System.out.println(e.getMessage());
				break;
			}
		}
	}

	private ServerSocket createServer(int port) {
		ServerSocket tmp = null;

		try {
			tmp = new ServerSocket(port);
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
		return tmp;
	}

	public static ServerSocket getS() {
		return s;
	}

	public static void setS(ServerSocket s) {
		Handler.s = s;
	}

	public Socket getClient() {
		return client;
	}

	public void setClient(Socket client) {
		this.client = client;
	}

	public ArrayList<Socket> getClients() {
		return clients;
	}

	public void setClients(ArrayList<Socket> clients) {
		this.clients = clients;
	}
}
